﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "imagewidget.h"
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

QImage cvMat2QImage(const cv::Mat &mat) {
	if (mat.type() == CV_8UC1) {
		QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
		image.setColorCount(256);
		for (int i = 0; i < 256; i++) {
			image.setColor(i, qRgb(i, i, i));
		}
		uchar *pSrc = mat.data;
		for (int row = 0; row < mat.rows; row++) {
			uchar *pDest = image.scanLine(row);
			memcpy(pDest, pSrc, static_cast<quint32>(mat.cols));
			pSrc += static_cast<quint32>(mat.step);
		}
		return image;
	}
	else if (mat.type() == CV_8UC3) {
		const uchar *pSrc = const_cast<const uchar *>(mat.data);
		QImage image(pSrc, mat.cols, mat.rows,
			static_cast<qint32>(mat.step), QImage::Format_RGB888);
		return image.rgbSwapped();
	}
	else if (mat.type() == CV_8UC4) {
		const uchar *pSrc = const_cast<const uchar *>(mat.data);
		QImage image(pSrc, mat.cols, mat.rows,
			static_cast<qint32>(mat.step), QImage::Format_ARGB32);
		return image.copy();
	}
	else if (mat.type() == 22) {
		cv::Mat src;
		mat.convertTo(src, CV_8UC3);
		const uchar *pSrc = const_cast<const uchar *>(src.data);
		QImage image(pSrc, src.cols, src.rows,
			static_cast<qint32>(src.step), QImage::Format_RGB888);
		return image.rgbSwapped();
	}
	else {
		return QImage();
	}
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
	Mat mat_qqq = imread("1.bmp", -1);
    QImage img = cvMat2QImage(mat_qqq);
    ui->setupUi(this);
	recvShowPicSignal(img);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::ShowXY(int x, int y)
{
	char tmp[32] = { 0 };
	sprintf(tmp, "%d,%d", x, y);
	ui->label_x->setText(tmp);
}

void MainWindow::recvShowPicSignal(QImage image)
{
    QPixmap ConvertPixmap=QPixmap::fromImage(image);//The QPixmap class is an off-screen image representation that can be used as a paint device
    QGraphicsScene  *qgraphicsScene = new QGraphicsScene;//要用QGraphicsView就必须要有QGraphicsScene搭配着用
    m_Image = new ImageWidget(&ConvertPixmap);//实例化类ImageWidget的对象m_Image，该类继承自QGraphicsItem，是自己写的类
	connect(m_Image, &ImageWidget::ImageClick, this, &MainWindow::ShowXY);
    int nwith = ui->ImageGraphic->width();//获取界面控件Graphics View的宽度
    int nheight = ui->ImageGraphic->height();//获取界面控件Graphics View的高度
    m_Image->setQGraphicsViewWH(nwith,nheight);//将界面控件Graphics View的width和height传进类m_Image中
    qgraphicsScene->addItem(m_Image);//将QGraphicsItem类对象放进QGraphicsScene中
    ui->ImageGraphic->setSceneRect(QRectF(-(nwith/2),-(nheight/2),nwith,nheight));//使视窗的大小固定在原始大小，不会随图片的放大而放大（默认状态下图片放大的时候视窗两边会自动出现滚动条，并且视窗内的视野会变大），防止图片放大后重新缩小的时候视窗太大而不方便观察图片
    ui->ImageGraphic->setScene(qgraphicsScene);//Sets the current scene to scene. If scene is already being viewed, this function does nothing.
    ui->ImageGraphic->setFocus();//将界面的焦点设置到当前Graphics View控件
}
